<template>
  <div class="project-tree-page">
    <header>
      <!-- 项目树划分变更 -->
      <Row type="flex" justify="start" align="middle">
        <Col span="4"><h2>项目树划分变更详情</h2></Col>
        <Col span="20"
          ><Button class="btn-color back" @click="backToRecordList"  type="primary"
            >返回</Button
          ></Col
        >
      </Row>
    </header>
    <header style="margin-top:30px">
      <Row type="flex" justify="start" align="middle">
        <Col span="5" class="plist-title" style="display:flex">
          <template v-for="(pItem, index) in pActiveList" >
            <p :class="pItem.isCheck ? 'active-p' : ''" :key="index" @click="changeP(index)">
              {{ pItem.title }}
            </p>
          </template>
        </Col>
        <Col span="19">
          <Button
            class="btn-color"
            @click="exportExcel"
            style="margin:0 15px"
            >导出excel</Button
          >
          <Button class="btn-color" style="margin-right:15px" :disabled="btnDisabled.copy" @click="copyTreeNode">复制层级</Button>
          <Button
            @click="submitPrimaryApproval"
            type="primary"
            :disabled="btnDisabled.primary"
            >提交审批</Button
          >
        </Col>
      </Row>
    </header>
    <section class="section">
      <Row type="flex" justify="start" align="top">
        <Col span="5">
          <Htdlist @getContractTree="getContractTree"  ref="htdList" :tree="treeData"/>
        </Col>
        <!-- 变更记录日志table列表 -->
        <Col span="18" style="margin:0 auto " v-show="showSwitch.isTablelog">
          <template>
            <p>变更日志</p>
            <Table border :columns="logColumns" :data="logData"></Table>
          </template>
        </Col>
        <!-- 变更记录项目树 -->
        <Col span="19" v-show="!showSwitch.isTablelog">
          <template>
            <div class="introduce" v-show="showSwitch.introduce">
              <p>变更说明:</p>
              <Input v-model="introduce" ref="input" placeholder="请输入本次变更说明"
            @on-blur="mouseLaeveIntroduce"  :disabled='btnDisabled.introduce'> </Input>
            </div>
            <!-- 旧项目树区域/edit编辑项目树 -->
            <section v-if="showSwitch.treeEditState" class="aside-tree">
              <Tree :data="treeData.newTree" expand-node :render="renderContent" @on-toggle-expand="sendSwitchNode"></Tree>
            </section>
            <!-- 旧项目树区域/view查看项目树 -->
            <section v-if="!showSwitch.treeEditState" class="aside-tree">
              <!--render自定义渲染 -->
              <Tree :data="treeData.newTree" expand-node :render="renderContent0" @on-toggle-expand="sendSwitchNode"></Tree>
            </section>
          </template>
        </Col>
        <!-- 审批侧边栏弹窗 -->
        <ApprovalSidebar
          :id="approval.approvalDataId"
          :type="approval.approvalType"
          model="default"
          ref="approvalSidebar"
           v-show="showSwitch.approvalSidebar"
        />
      </Row>
    </section>
    <Modal
      ref="modal"
      @getContractTree="getContractTree"
      :htd="htd"
      :nodeId="nodeId"
      :parentId="parentId"
      :tree="treeData"
    />
  </div>
</template>
<script>
import apiObj from '@/api/project-partition.js';
import ApprovalSidebar from '@/components/approval-sidebar/index.js';
import { ApprovalType } from '@/config/cfg.js';
import Htdlist from './htd-list';
import Modal from './modal';
import config from '@/config';
const baseUrl =
  process.env.NODE_ENV === 'development'
    ? config.baseUrl.dev
    : config.baseUrl.pro;

export default {
  name: 'new-tree',
  data () {
    return {
      htd: {
        htdId: 0
      },
      // 合同段ID
      nodeId: 0,
      parentId: 0,
      // 树
      treeData: {
        // 表示新树
        tree: 'old',
        newTree: [],
        oldTree: []
      },
      // 变更记录/变更后
      pActiveList: [
        { title: '变更记录', isCheck: true },
        { title: '变更后', isCheck: false }
      ],

      showSwitch: {
        // 显示编辑树或者查看树
        treeEditState: false,
        // 是否是变更记录日志table
        isTablelog: true,
        // 是否显示新增按钮组
        btnGroup: false,
        // 是否显示变更简介
        introduce: false,
        // 审批流程侧边栏是否显示
        approvalSidebar: false
      },
      // 按钮是否可点
      btnDisabled: {
        // 提交审批按钮
        primary: true,
        // 变更简介文本框可点
        introduce: false,
        // 复制层级
        copy: true
      },
      // 审批相关
      approval: {
        approvalDataId: '', // 审批数据id
        approvalType: ApprovalType.SP_TYPE_XMHF // 审批数据类型
      },
      switchNodeId: -1, // 展开闭合的节点nodeId
      switchNodeExpand: null, // 展开闭合的节点expand
      dataMap: {}, // tree数据map
      //   变更日志列表
      logColumns: [
        {
          title: '层级',
          key: 'oldLevelName',
          align: 'center'
        },
        {
          title: '类型',
          key: 'oldLevelType',
          align: 'center'
        },
        {
          title: '编号',
          key: 'oldcode',
          align: 'center'
        },
        {
          title: '名称',
          key: 'nodeName',
          align: 'center',
          width: 120
        },
        {
          title: '顺序',
          key: 'oldsort',
          align: 'center'
        },
        {
          title: '变更为',
          key: 'pname',
          align: 'center',
          width: 200
        },
        {
          title: '层级',
          key: 'newLevelName',
          align: 'center'
        },
        {
          title: '类型',
          key: 'newLevelType',
          align: 'center'
        },
        {
          title: '编号',
          key: 'newCode',
          align: 'center'
        },
        {
          title: '名称',
          key: 'newName',
          align: 'center',
          width: 120
        },
        {
          title: '顺序',
          key: 'newSort',
          align: 'center'
        }
      ],
      // 变更简介介绍
      introduce: '',
      // 变更日志列表
      logData: []
    };
  },
  methods: {
    sendSwitchNode (e) {
      console.log('e', e);
      this.switchNodeId = e.nodeId;
      this.switchNodeExpand = e.expand;
      let map = this.changeTreeToMap(this.treeData.newTree);
      this.$nextTick(() => {
        this.$refs['modal'].switchExpand(map);
      });
    },
    // 把treeData转成map
    changeTreeToMap (list) {
      let map = this.dataMap;
      const handleTerrData = list => {
        list.forEach(row => {
          map[row.nodeId] = map[row.nodeId] || false;
          if (row.children) {
            handleTerrData(row.children);
          }
        });
      };
      handleTerrData(list);
      const switchId = this.switchNodeId;
      const switchExpand = this.switchNodeExpand;
      for (let key in map) {
        if (switchId !== -1) {
          if (key == switchId) {
            map[key] = switchExpand;
          }
        }
      }
      return map;
    },
    // 项目树(edit可编辑)
    renderContent (h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-block',
            width: '100%'
          },
          class:
            data.nodeClick === true ? 'tree-item  level-click' : 'tree-item '
        },
        [
          h('span', [
            h('Icon', {
              props: {
                type: 'ios-paper-outline'
              },
              style: {
                marginRight: '8px'
              }
            }),
            h(
              'span',
              {
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.btnDisabled.addBrother = false;
                    this.btnDisabled.copy = false;
                  }
                }
              },
              data.nodeName
            )
          ]),
          h(
            'span',
            {
              style: {
                display: 'inline-block',
                marginLeft: '32px'
              },
              class: 'tree-item-btn'
            },
            [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-add-circle-outline',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.addTreeNodeEvent(2);
                  }
                }
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-create-outline',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.editTreeNodeEvent();
                  }
                }
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'md-trash',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.deleteTreeNodeEvent(data);
                  }
                }
              })
            ]
          )
        ]
      );
    },
    // 查看的项目树，不可编辑
    renderContent0 (h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-block',
            width: '100%'
          },
          class:
            data.nodeClick === true ? 'tree-item  level-click' : 'tree-item '
        },
        [
          h('span', [
            h('Icon', {
              props: {
                type: 'ios-paper-outline'
              },
              style: {
                marginRight: '8px'
              }
            }),
            h(
              'span',
              {
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                  }
                }
              },
              data.nodeName
            )
          ]),
          h(
            'span',
            {
              style: {
                display: 'inline-block',
                marginLeft: '32px'
              },
              class: 'tree-item-btn'
            },
            [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'md-eye',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.viewTreeNodeEvent();
                  }
                }
              })
            ]
          )
        ]
      );
    },
    // 点击合同段某一层级
    async getContractTree (htdId, parentId, nodeId, isChecked, state, projectPart, flag) {
      console.log('flag', flag);
      this.parentId = parentId;
      this.nodeId = nodeId;
      this.htd.htdId = htdId;
      this.btnDisabled.primary = state; // 是否禁点提交审批
      this.showSwitch.introduce = !state;
      this.showSwitch.approvalSidebar = !isChecked;
      this.btnDisabled.addBrother = flag;
      this.btnDisabled.copy = flag;
      console.log('提交审批状态现在是啥？', state);
      this.confirmBtnTreeStates(state);
      this.approval.approvalDataId = htdId;

      let send = {
        nodeId: htdId
      };
      // 请求项目树
      try {
        const resp = await apiObj.getContractOldTree(send);
        const datas = resp.data.data;
        this.treeData.newTree = datas.nodes;
        this.introduce = datas.comments;
      } catch (error) {}
      // 请求变更日志
      try {
        const resp1 = await apiObj.changeDetialList(send);
        console.log('日志？', resp1);
        this.logData = resp1.data.data;
      } catch (error) {}
    },
    // 判断新增按钮组是否显示，判断当前树是编辑还是只可查看
    confirmBtnTreeStates (state) {
      if (!state) {
        this.showSwitch.btnGroup = true;
        this.showSwitch.treeEditState = true;
      } else {
        // 表示提交按钮禁用，即树不可编辑
        this.showSwitch.btnGroup = false;
        this.showSwitch.treeEditState = false;
      }
    },
    // 编辑提交变更简介
    async mouseLaeveIntroduce () {
      const send = { htdId: this.htd.htdId, comments: this.introduce };
      const resp = await apiObj.recodeIntroduce(send);
      console.log('resp', resp);
      this.showSwitch.isIntroduceView = true;
      this.$Message.success('提交成功！');
    },
    // 鼠标离开提交变更简介
    // 复制项目树某节点层级
    async copyTreeNode () {
      console.log('复制');
      const send = { nodeId: this.nodeId, htdId: this.htd.htdId };
      const resp = await apiObj.copyTreeNode(send);
      this.$nextTick(() => {
        this.$refs['modal'].refreshContractTree();
      });
      console.log('复制的节点', resp);
    },
    // 提交审批：把项目树和审批流程提交
    async submitPrimaryApproval () {
      const approvalList = this.$refs.approvalSidebar.getApprovalData();
      if (approvalList && approvalList.length === 0) {
        this.$Modal.warning({
          title: '提示',
          content: '请至少添加一个审批节点'
        });
      } else {
        const send = {
          busVo: {
            dataid: this.htd.htdId
          },
          list: approvalList
        };
        try {
          const resp = await apiObj.submitApprovalBtn(send);
          console.log('提交审批后的resp', resp);
          this.confirmBtnTreeStates(true);
          this.btnDisabled.primary = true;
          this.$refs.htdList.getContractList();
        } catch (error) {}
      }
    },
    // 新增同级/新增下级/树新增按钮事件
    addTreeNodeEvent (type) {
      this.$nextTick(() => {
        this.$refs['modal'].showTreeNodeModal(type);
      });
    },
    // 编辑节点按钮事件
    editTreeNodeEvent () {
      this.$nextTick(() => {
        this.$refs['modal'].editTreeNodeModal();
      });
    },
    // 删除节点按钮事件
    deleteTreeNodeEvent (node) {
      this.$nextTick(() => {
        this.$refs['modal'].deleteTreeNodeModal(node);
      });
    },
    // 查看节点按钮事件
    viewTreeNodeEvent () {
      this.$nextTick(() => {
        this.$refs['modal'].viewTreeNodeModal();
      });
    },
    // 给nodeId和parentId赋值
    nodeidAssignment (data) {
      this.nodeId = data.nodeId;
      this.parentId = data.parentId;
    },
    // 切换变更详情/变更后
    changeP (index) {
      const list = this.pActiveList;
      for (let i = 0; i < list.length; i++) {
        list[i].isCheck = false;
      }
      list[index].isCheck = true;
      if (list[0].isCheck) {
        this.showSwitch.isTablelog = true;
      } else {
        this.showSwitch.isTablelog = false;
      }
    },
    // async changeDetialList () {
    //   var htdId = this.htd.htdId;
    // },
    // 导出Excel
    async exportExcel () {
      let url = `${baseUrl}/pt/export?id=${this.htd.htdId}`;
      // url = 'http://192.168.0.233:8999/pt/export';
      window.open(url);
    },
    // 由变更记录切换到变更列表页
    backToRecordList () {
      this.$router.go(-1);
    }
  },
  components: {
    Htdlist,
    Modal,
    ApprovalSidebar
  },
  mounted () {
    this.treeData.tree = 'old';
    console.log('0?1', this.$route.query.state);
    this.showSwitch.treeEditState = this.$route.query.state;
  }
};
</script>
<style lang="less" scoped>
@fontSize: 20px;
@shortWH: 5px;
@middleWH: 20px;
@longWH: 100px;
body {
  height: 100%;
  padding: 0 !important;
  .project-tree-page {
    width: 100%;
    height: 100%;
    .btn-color {
      border-color: #5cadff;
      color: #5cadff;
    }
    .back{
      border-color:#ffffff ;
      color: #ffffff;
    }
    .plist-title {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      p {
        cursor: pointer;
        width: 50%;
        font-size: 0.8 * @fontSize;
        border-bottom: 1px solid gray;
        line-height: 2 * @middleWH;
      }
      .active-p {
        color: rgb(226, 140, 11);
        box-sizing: border-box;

        border-bottom: 1px solid rgb(226, 140, 11);
      }
    }
    .section {
      margin-top: 2 * @shortWH;
      .aside-tree {
        .tree-item:hover {
          cursor: pointer;
        }
      }
      .introduce{
        color: red;
        font-weight: bold;
        margin-left: 4*@shortWH;
        display: flex;
        align-items: center;
        p{
          width: 3*@middleWH;
        }
      }
    }
  }
}
</style>
